{ "cells": [ { "cell_type": "markdown", "metadata": { "school_cell_uuid": "e4d22401be624bce89269e857bb8111d" }, "source": [ "# 4.3 데이터프레임 고급 인덱싱" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "89ee86967d3347769b353c7abebc7f05" }, "source": [ "데이터프레임에서 특정한 데이터만 골라내는 것을 인덱싱(indexing)이라고 한다. 앞 절에서는 라벨, 라벨 리스트, 인덱스데이터(정수) 슬라이스의 3가지 인덱싱 값을 사용하여 인덱싱을 하는 방법을 공부하였다.\n", "그런데 Pandas는 numpy행렬과 같이 쉼표를 사용한 `(행 인덱스, 열 인덱스)` 형식의 2차원 인덱싱을 지원하기 위해 다음과 같은 특별한 인덱서(indexer) 속성도 제공한다.\n", "\n", "* `loc` : 라벨값 기반의 2차원 인덱싱\n", "* `iloc` : 순서를 나타내는 정수 기반의 2차원 인덱싱" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "2c89840460d9498583d9b5195a80a395" }, "source": [ "## `loc` 인덱서" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "706d8afe07a44144bb6bee8ae579440c" }, "source": [ "`loc` 인덱서는 다음처럼 사용한다.\n", "\n", "```\n", "df.loc[행 인덱싱값]\n", "```\n", "또는\n", "```\n", "df.loc[행 인덱싱값, 열 인덱싱값]\n", "```\n", "\n", "\n", "이 때 인덱싱 값은 다음 중 하나이다. 행 인덱싱값은 정수 또는 행 인덱스데이터이고 열 인덱싱값은 라벨 문자열이다.\n", "\n", "* 인덱스데이터\n", "* 인덱스데이터 슬라이스\n", "* 인덱스데이터 리스트\n", "* 같은 행 인덱스를 가지는 불리언 시리즈 (행 인덱싱의 경우)\n", "* 또는 위의 값들을 반환하는 함수\n" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "9b81b480614b417baf713d69f887f9b2" }, "source": [ "다음과 같은 데이터프레임을 예로 들자." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "school_cell_uuid": "2d3bc9c1437b4b0d9f3d39013bca8932" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
a10111213
b14151617
c18192021
\n", "
" ], "text/plain": [ " A B C D\n", "a 10 11 12 13\n", "b 14 15 16 17\n", "c 18 19 20 21" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.DataFrame(np.arange(10, 22).reshape(3, 4),\n", " index=[\"a\", \"b\", \"c\"],\n", " columns=[\"A\", \"B\", \"C\", \"D\"])\n", "df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 인덱싱값을 하나만 받는 경우" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "c5b451908cb5449d84c290fab8b002bf" }, "source": [ "만약 `loc` 인덱서를 사용하면서 인덱스를 하나만 넣으면 행(row)을 선택한다.\n", "\n", "인덱스데이터가 \"a\"인 행을 고르면 해당하는 행이 시리즈로 출력된다. 시리즈라서 상하로 길게 출력되기는 했지만 행을 가져오고 있다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "school_cell_uuid": "5d294869b93d4e51bb4938b9e46d25ad" }, "outputs": [ { "data": { "text/plain": [ "A 10\n", "B 11\n", "C 12\n", "D 13\n", "Name: a, dtype: int64" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[\"a\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "인덱스데이터의 슬라이스도 가능하다." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "school_cell_uuid": "24b94f311bd14f8f9d83a12ba63623c9" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
b14151617
c18192021
\n", "
" ], "text/plain": [ " A B C D\n", "b 14 15 16 17\n", "c 18 19 20 21" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[\"b\":\"c\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "이 때는 사실 `loc`를 쓰지 않는 경우과 같다." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "school_cell_uuid": "24b94f311bd14f8f9d83a12ba63623c9" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
b14151617
c18192021
\n", "
" ], "text/plain": [ " A B C D\n", "b 14 15 16 17\n", "c 18 19 20 21" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df[\"b\":\"c\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "인덱스데이터의 리스트도 된다." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "school_cell_uuid": "24b94f311bd14f8f9d83a12ba63623c9" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
b14151617
c18192021
\n", "
" ], "text/plain": [ " A B C D\n", "b 14 15 16 17\n", "c 18 19 20 21" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[[\"b\", \"c\"]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "이 때는 `loc`를 쓰지 않으면 KeyError 오류가 발생한다.." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "school_cell_uuid": "24b94f311bd14f8f9d83a12ba63623c9" }, "outputs": [], "source": [ "# df[[\"b\", \"c\"]] # KeyError" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "데이터베이스와 같은 인덱스를 가지는 불리언 시리즈도 행을 선택하는 인덱싱값으로 쓸 수 있다." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "a False\n", "b False\n", "c True\n", "Name: A, dtype: bool" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.A > 15" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
c18192021
\n", "
" ], "text/plain": [ " A B C D\n", "c 18 19 20 21" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[df.A > 15]" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "d8830de14fce4f8098e50099979a8445" }, "source": [ "인덱스 대신 인덱스 값을 반환하는 함수를 사용할 수도 있다. 다음 함수는 A열의 값이 12보다 큰 행만 선택한다." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "school_cell_uuid": "9a545b4b09624035bbb9b268c6318212" }, "outputs": [], "source": [ "def select_rows(df):\n", " return df.A > 15" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "school_cell_uuid": "cc467ac94f5940b1b41a59967a59aaba" }, "outputs": [ { "data": { "text/plain": [ "a False\n", "b False\n", "c True\n", "Name: A, dtype: bool" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "select_rows(df)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "school_cell_uuid": "644b4eb7083c4c4f82ea214aa1a31cda" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
c18192021
\n", "
" ], "text/plain": [ " A B C D\n", "c 18 19 20 21" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[select_rows(df)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`loc` 인덱서가 없는 경우에 사용했던 라벨 인덱싱이나 라벨 리스트 인덱싱은 불가능하다." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "# df.loc[\"A\"] # KeyError" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "# df.loc[[\"A\", \"B\"]] # KeyError" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "5a28b9323b404bb6896b6668a9fa3b76" }, "source": [ "원래 (행) 인덱스값이 정수인 경우에는 슬라이싱도 라벨 슬라이싱 방식을 따르게 된다. 즉, 슬라이스의 마지막 값이 포함된다." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "school_cell_uuid": "cb220ad3b3534cf8a8bee67a6b0a536c" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
010111213
114151617
218192021
322232425
\n", "
" ], "text/plain": [ " A B C D\n", "0 10 11 12 13\n", "1 14 15 16 17\n", "2 18 19 20 21\n", "3 22 23 24 25" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df2 = pd.DataFrame(np.arange(10, 26).reshape(4, 4), columns=[\"A\", \"B\", \"C\", \"D\"])\n", "df2" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "school_cell_uuid": "fc2e1fd80824455ea360ac2cdb5a6b6f" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
114151617
218192021
\n", "
" ], "text/plain": [ " A B C D\n", "1 14 15 16 17\n", "2 18 19 20 21" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df2.loc[1:2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "정리하면 다음과 같다.\n", "\n", "| 인덱싱 값 | 가능 | 결과 | 자료형 | 추가사항 |\n", "|-|-|-|-|-|\n", "| 행 인덱스값(정수) | O | 행 | 시리즈 | |\n", "| 행 인덱스값(정수) 슬라이스 | O | 행 | 데이터프레임 | `loc`가 없는 경우와 같음 |\n", "| 행 인덱스값(정수) 리스트 | O | 행 | 데이터프레임 | |\n", "| 불리언 시리즈 | O | 행 | 데이터프레임 | 시리즈의 인덱스가 데이터프레임의 행 인덱스와 같아야 한다. |\n", "| 불리언 시리즈를 반환하는 함수 | O | 행 | 데이터프레임 | |\n", "| 열 라벨 | X | | | `loc`가 없는 경우에만 쓸 수 있다. |\n", "| 열 라벨 리스트 | X | | | `loc`가 없는 경우에만 쓸 수 있다. |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 인덱싱값을 행과 열 모두 받는 경우" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "ae0f75a624944575962577a399ef6dc0" }, "source": [ "인덱싱값을 행과 열 모두 받으려면 `df.loc[행 인덱스, 열 인덱스]`와 같은 형태로 사용한다. 행 인덱스 라벨값이 `a`, 열 인덱스 라벨값이 `A`인 위치의 값을 구하는 것은 다음과 같다." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "school_cell_uuid": "013adc21505544cd8d828f9120b0cd28" }, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[\"a\", \"A\"]" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "94a76dc9304442b881526d28307df3d7" }, "source": [ "인덱싱값으로 라벨 데이터의 슬라이싱 또는 리스트를 사용할 수도 있다." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "school_cell_uuid": "f1ae86b9e90b4dccae9f25718934a44a" }, "outputs": [ { "data": { "text/plain": [ "b 14\n", "c 18\n", "Name: A, dtype: int64" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[\"b\":, \"A\"]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "school_cell_uuid": "98d25e608dd04706b8eb281cf295e3db" }, "outputs": [ { "data": { "text/plain": [ "A 10\n", "B 11\n", "C 12\n", "D 13\n", "Name: a, dtype: int64" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[\"a\", :]" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "school_cell_uuid": "99c6141e43904558a980d6d9abc88e2f" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
BD
a1113
b1517
\n", "
" ], "text/plain": [ " B D\n", "a 11 13\n", "b 15 17" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[[\"a\", \"b\"], [\"B\", \"D\"]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "행 인덱스가 같은 불리언 시리즈나 이러한 불리언 시리즈를 반환하는 함수도 행의 인덱싱값이 될 수 있다." ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "school_cell_uuid": "841546c45bc54ae0990e2f7198486b50" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
CD
b1617
c2021
\n", "
" ], "text/plain": [ " C D\n", "b 16 17\n", "c 20 21" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.loc[df.A > 10, [\"C\", \"D\"]]" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "bbd3c551381f4dd7b7cf12a260d921f6" }, "source": [ "## `iloc` 인덱서" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "cd5e097e6f28455eabdf36fb9ce37119" }, "source": [ "`iloc` 인덱서는 `loc` 인덱서와 반대로 라벨이 아니라 순서를 나타내는 정수(integer) 인덱스만 받는다. 다른 사항은 `loc` 인덱서와 같다." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "school_cell_uuid": "446d9e6d78424c10bf2ab6245fc82cca" }, "outputs": [ { "data": { "text/plain": [ "11" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.iloc[0, 1]" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "school_cell_uuid": "239fbc92ad81434c9193f33643a34b3c" }, "outputs": [ { "data": { "text/plain": [ "a 12\n", "b 16\n", "Name: C, dtype: int64" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.iloc[:2, 2]" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "school_cell_uuid": "cde66e35ab174df4a3abb01e101b282e" }, "outputs": [ { "data": { "text/plain": [ "C 12\n", "D 13\n", "Name: a, dtype: int64" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.iloc[0, -2:]" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "school_cell_uuid": "20c5b726e62e4faca758b5c520c208cd" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
BC
c1920
\n", "
" ], "text/plain": [ " B C\n", "c 19 20" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.iloc[2:3, 1:3]" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "fc98d52efb844f8295e6285a295275a6" }, "source": [ "`loc` 인덱서와 마찬가지로 인덱스가 하나만 들어가면 행을 선택한다." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "school_cell_uuid": "fe9099f099974673aa48731b3c9f8fba" }, "outputs": [ { "data": { "text/plain": [ "A 18\n", "B 19\n", "C 20\n", "D 21\n", "Name: c, dtype: int64" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.iloc[-1]" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "school_cell_uuid": "86e4a000510b4a1a94bf2f2e114444d9" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABCD
a10111213
b14151617
c36384042
\n", "
" ], "text/plain": [ " A B C D\n", "a 10 11 12 13\n", "b 14 15 16 17\n", "c 36 38 40 42" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.iloc[-1] = df.iloc[-1] * 2\n", "df" ] }, { "cell_type": "markdown", "metadata": { "bootstrap": { "panel": { "class": "panel-default" } }, "school_cell_uuid": "269c72d94eac4e4c948cb3560fd9b5e9" }, "source": [ "````{admonition} 연습 문제 4.3.1\n", "\n", "1. 모든 행과 열에 라벨을 가지는 5 x 5 이상의 크기를 가지는 데이터프레임을 만든다. \n", "2. 10가지 이상의 방법으로 특정한 행과 열을 선택한다.\n", "````" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "celltoolbar": "Edit Metadata", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false } }, "nbformat": 4, "nbformat_minor": 4 }